package com.moonce.api.web.interceptor;

import com.moonce.api.model.vo.ResultJson;
import com.moonce.api.util.JwtUtil;
import com.moonce.api.util.LogUtils;
import com.moonce.api.util.TokenUtils;
import com.moonce.api.util.constant.Code;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 马路遥(229010812 @ qq.com)
 * @version V1.0
 * @Title: springmvc-demo
 * @Package com.moonce.api.web.interceptor
 * @Description: token拦截判断
 * @Date 2017-12-14 11:30
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenInterceptor.class);
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
//        String requestUrl = request.getScheme() //当前链接使用的协议
//                +"://" + request.getServerName()//服务器地址
//                + ":" + request.getServerPort() //端口号
//                + request.getContextPath() //应用名称，如果应用名称为
//                + request.getServletPath() //请求的相对url
//                + "?" + request.getQueryString();
//        System.out.println(CommonUtils.getURLDecoderString(requestUrl));
        try {
            Claims claims = jwtUtil.parseJWT(token);
            Long userId = TokenUtils.getUserId(claims.getSubject());
            if (userId == null) {
                PrintWriter out = response.getWriter();
                out.print(ResultJson.toJson(Code.AUTH_FAIL_CODE,Code.AUth_MSG,Code.NULL_STR));
                return false;
            }
            request.setAttribute("userId", userId);
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            PrintWriter out = response.getWriter();
            out.print(ResultJson.toJson(Code.AUTH_FAIL_CODE,Code.AUth_ERROR_MSG,Code.NULL_STR));
            LOGGER.error("鉴权失败：{},错误信息：{}",token, LogUtils.getException(e));
        }
        return false;
    }
}
